package com.zd.file.brower.controller;

import com.zd.file.brower.cache.RootPathCache;
import com.zd.file.brower.service.ReloadPathService;
import com.zd.file.brower.vo.FileVo;
import com.zd.file.common.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController {
    static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    ReloadPathService reloadPathService;
    @GetMapping("/{index:\\d+}/**")
    public String list(@PathVariable("index") Integer index, HttpServletRequest request, ModelMap modelMap, HttpServletResponse response){
        String path = getPath(index,request);
        if (StringUtils.isEmpty(path)){
            return "404";
        }
        logger.info("显示目标目录:{}",path);
        File file = new File(path);
        if (file.exists()) {
            // 路径或文件存在 继续
            if(file.isDirectory()) {
                modelMap.put("listFile", getChildFileVo(file));
                return "file/dir";
            }else {
                response.setContentType(FileUtils.getContentTypeByFile(file));
                //response.setHeader("Content-Disposition", "attachment; filename=" +file.getName());
                FileInputStream in = null;
                ServletOutputStream outputStream = null;
                try {
                    in = new FileInputStream(file);
                    int length = in.available();
                    byte data[] = new byte[length];
                    response.setContentLength(length);
                    in.read(data);
                    outputStream = response.getOutputStream();
                    outputStream.write(data);
                    outputStream.flush();
                } catch (Exception e) {
                    logger.error("Read File error !",e);
                }finally {
                    if (outputStream != null){
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            logger.warn("close outputstream error");
                        }
                    }
                    if (in != null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            logger.warn("close inputstream error");
                        }
                    }
                }
                return null;
            }
        }else {
            // 路径或文件不存在
            return "404";
        }
    }

    private List<FileVo> getChildFileVo(File file) {
        List<FileVo> list = new ArrayList<>();
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File f:files) {
                list.add(new FileVo(f));
            }
        }
        return list;
    }

    private String getPath(Integer index,HttpServletRequest request){
        // 检查 路径是否合法
        if (index == null ){
            return null;
        }
        String rootpath = RootPathCache.getRootPath(index);
        if (StringUtils.isEmpty(rootpath)) {
            return null;
        }
        // 获取全路径
        String path = null;
        try {
            path = URLDecoder.decode(request.getRequestURI(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("path decode error",e);
        }
        // 截取目标路径
        path = path.substring(request.getContextPath().length()+6+(index+"").length());
        if (!path.startsWith(System.getProperty("file.separator"))) {
            path = System.getProperty("file.separator")+path;
        }
        // "/"交由子目录处理原则
        if (path.endsWith("/")) {
            path = path.substring(0,path.length() -1);
        }
        return rootpath+path;
    }

}
